package com.ita.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import com.ita.dao.TenderRecordDao;
import com.ita.pojo.TenderRecord;

@Repository(value = "tenderRecordDao")
public class TenderRecordDaoImpl implements TenderRecordDao {

	@PersistenceContext(name = "unit")
	private EntityManager manager;

	@Override
	public TenderRecord add(TenderRecord t) {

		manager.persist(t);
		return t;
	}

	@Override
	public int UpdateRecord(String id, int state) {

		int result = 0;
		try {
			String pql = "update TenderRecord t set t.state=:state where t.id=:id";
			result = manager.createQuery(pql).setParameter("state", state).setParameter("id", id).executeUpdate();
		} catch (Exception e) {
			return result;
		}
		return result;
	}

	@Override
	public int UpdateRecord(String mid, int state, String activityId) {
		
		int result = 0;
		try {
			String pql = "update TenderRecord t set t.state=:state where t.m_id=:mid and t.activity_id=:activityId";
			result = manager.createQuery(pql).setParameter("state", state).setParameter("mid", mid)
					.setParameter("activityId", activityId).executeUpdate();
		} catch (Exception e) {
			return result;
		}
		return result;
	}

	@Override
	public TenderRecord find(String activityId, String mid) {
		TenderRecord t = null;
		try {
			String pql = "select t from TenderRecord t where t.m_id=:mid and t.activity_id=:activityId";
			t = (TenderRecord) manager.createQuery(pql).setParameter("activityId", activityId).setParameter("mid", mid).getSingleResult();
		} catch (Exception e) {
			return t;
		}
		return t;
	}

	@Override
	public List<TenderRecord> findAll(String mid) {
		try {
			String pql = "select t from TenderRecord t where t.m_id=:mid order by t.create_time desc";
			return manager.createQuery(pql,TenderRecord.class).setParameter("mid", mid).getResultList();
		} catch (Exception e) {
			return new ArrayList<>();
		}
	}
}
